﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace UIShare
{
    [DebuggerStepThrough]
    public class UIOperManager
    {
        public static void SaveData(Func<bool> saveAction, string completeMsg)
        {
            SaveData(null, saveAction, completeMsg,null);
        }

        public static void SaveData(Func<bool> saveAction, string completeMsg, Action successAction)
        {
            SaveData(null, saveAction, completeMsg, successAction);
        }

        public static void SaveData(Func<bool> validateFunc, Func<bool> saveAction, string completeMsg)
        {
            SaveData(
                    validateFunc,
                    saveAction,
                    completeMsg,
                    null
                );
        }

        public static void SaveData(Func<bool> validateFunc, Func<bool> saveAction, string completeMsg, Action successAction)
        {
            SaveData(
                    validateFunc,
                    saveAction,
                    () =>
                    {
                        if (!string.IsNullOrEmpty(completeMsg))
                            MsgBox.Info(completeMsg);
                        if (successAction != null)
                            successAction.Invoke();
                    },
                    (ex) =>
                    {
                        MsgBox.Error(ex.Message);
                    },
                    null
                );
        }

        public static void SaveData(Func<bool> validateFunc, Func<bool> saveAction, Action completeAction, Action<Exception> errorAction, Action finallyAction)
        {
            bool validateResult = true;

            if (validateFunc != null)
                validateResult = validateFunc.Invoke();

            if (!validateResult)
                return;

            if (saveAction == null)
                return;

            try
            {
                bool result = saveAction.Invoke();

                if (completeAction != null && result)
                    completeAction.Invoke();

            }
            catch (Exception ex)
            {
                if (errorAction != null)
                    errorAction.Invoke(ex);
            }
            finally
            {
                if (finallyAction != null)
                    finallyAction.Invoke();
            }
        }
    }
}
